import React,{ Component } from 'react';
import {
	Modal,
	Typography,
	Select,
	Space,
	Card,
	Tree,
	Button,
	Form,
	Input
} from 'antd';
// import { FileOutlined } from '@ant-design/icons';
import {
	groupField,
	groupFieldData,
	resetGroupField,
} from 'src/services/DataManage';

import { FormInstance } from 'antd/lib/form';

interface Cprops {
    createGropVisible:boolean
    handleVisible:any
    addGroup:any
}

const AddGroup = ( props:Cprops ) => {
	const [ form ] = Form.useForm();

	const handleOk = () => {
		form.validateFields().then( value => {
			props.addGroup( value['name'] );
			handleCancle();
		} );
	};

	const handleCancle = () => {
		props.handleVisible();
		form.resetFields();
	};

	return (
		<Modal title={'新建分组'} okText={'确定'}
			visible={props.createGropVisible}
			cancelText={'取消'} onOk={handleOk}
			onCancel={handleCancle}>
			<Form form={form}>
				<Form.Item name={'name'}
					label={'名称'}
					rules={[ { required: true, message: '请输入分组名称' } ]}>
					<Input/>
				</Form.Item>
			</Form>
		</Modal>
	);
};


interface Iprops {
    modalVisibleValue:boolean
    FieldData:any
    modalVisible:any
    joinComponentFunc:any
    setOutDataFunc:any
}

class GroupField extends Component<Iprops> {

    formRef = React.createRef<FormInstance>()

    state = {
    	groups: [],
    	selectField: '',
    	selcetData: [],
    	createGropVisible: false,
    	delKeys: [],
    	expandedKeys: [],
    }

    //关闭字段分组弹框
    handleCancle = () => {
    	this.setState( {
    		groups: [],
    		selectField: '',
    		selcetData: [],
    		createGropVisible: false,
    		delKeys: [],
    		expandedKeys: [],
    	} );
    	let data = this.props.FieldData;
    	delete data.edit;
    	this.props.setOutDataFunc( data );
    	this.props.modalVisible( 'fieldGroupVisible',false );
    	this.formRef.current.resetFields();
    }

    //提交
    handleSubmit = async () => {
    	const { modelId } = this.props.FieldData;
    	console.log( this.state.groups );
    	let g = this.state.groups.filter( item => item.type.startsWith( 'parent' ) ).map( item => {
    		return { 'sources': item.children.map( item => item.key ), 'target': item.key };
    	} );
    	let enm = { 'groups': g, 'name': this.state.selectField, 'other': '其他' };
    	let data = { 'fields': { 'enumFields': [ { ...enm } ], 'sectFields': [] }, 'modelId': modelId, 'position': 1 };
    	let info = null;
    	//编辑修改
    	if( this.props.FieldData.edit ) {
    		const { code,name } = this.props.FieldData;
    		info = await resetGroupField( { data: { 'fields': { 'enumFields': [ { ...enm } ], 'sectFields': [] },
    			componentCode: code,componentName: name,'position': 1 } } );
    	}else {
    		//引入新增
    		info = await groupField( { data: data } );
    	}

    	if ( info.data.success ) {
    		const data =  info.data.data;
    		let toData = { ...data,
    			groups: this.state.groups,
    			selcetData: this.state.selcetData,
    			selectField: this.state.selectField,
    			edit: this.props.FieldData.edit,
    			nodeType: 'GroupField',
    			style: { 'primaryColor': '#0066FF' },
    			shape: 'SimplicityNode' };
    		this.props.joinComponentFunc( this.props.FieldData,toData,{} );
    		this.handleCancle();
    	}

    }

    //关闭分组弹框
    handleVisible = () => {
    	this.setState( { createGropVisible: false } );
    }

    //打开分组弹框
    addFile = () => {
    	this.setState( { createGropVisible: true } );
    	// this.setState( { files: [ ...this.state.files,{ 'name': 'tets' } ] } );
    }

    //添加一个分组
    addGroup = name => {
    	const { groups,delKeys } = this.state;
    	this.setState( { groups: [ { key: name,title: name,type: 'parent',
    		children: [ ...groups.filter( item => delKeys.includes( item.key ) && !item.type.startsWith( 'parent' ) ) ] } ,
    	...groups.filter( item => !delKeys.includes( item.key )|| item.type.startsWith( 'parent' ) ) ],
    	expandedKeys: [ ...this.state.expandedKeys,name ] } );
    }

    //删除一个数据
    handleDel = ( ) => {
    	const { groups,delKeys } = this.state;
    	this.setState( {
    		'groups': groups.filter( item => !delKeys.includes( item.key ) ).map( item => {
    			if( item.children ) {
    				item.children = item.children.filter( item => !delKeys.includes( item.key ) );
    				return item;
    			}
    			return item;
    		} ),
    	},() => {return;} );
    }

    onCheck = checkedKeys => {
    	this.setState( { delKeys: checkedKeys },() => {} );
    };

    componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
    	if( this.props.modalVisibleValue!== prevProps.modalVisibleValue && this.props.FieldData.selectField &&this.props.FieldData.edit ) {
    		this.setState( {
    			groups: [ ...this.props.FieldData.groups ],
    			// selcetData: [ ...this.props.FieldData.selcetData ],
    			selectField: this.props.FieldData.selectField,
    		},
    		() => {this.formRef.current.setFieldsValue( { select: this.props.FieldData.selectField } );} );
    	}
    }


    fieldChange = async value => {
    	const { id,modelId } = this.props.FieldData;
    	const info = await groupFieldData( { data: { 'componentId': id, 'field': value, 'modelId': modelId } } );
    	if( info.data.success ) {
    		const data = info.data.data;
    		let slist = data.map( item => {
    			return {
    				title: item,
    				key: item,
    				type: 'node',
    				isLeaf: true,
    			};
    		} );
    		this.setState( { createGropVisible: false,
    			delKeys: [],
    			expandedKeys: [],
    			selectField: value,
    			// selcetData: [ ...slist ],
    			groups: [ ...slist ] } );
    	}
    }

    onDragEnd = info => {
    }

    onDragEnter = info => {
    	// expandedKeys 需要受控时设置
    	this.setState( {
    		expandedKeys: info.expandedKeys,
    	} );
    };

    indexFind = ( arr,key ) => {
    	return arr.findIndex( ( value, index, arr ) => {
    		return value.key === key;
    	} );
    }


    onDrop = info => {
    	console.log( info );
    	const dropKey = info.node.key;
    	const dropType = info.node.type;
    	const dragKey = info.dragNode.key;
    	const dragType = info.dragNode.type;
    	const dropPos = info.node.pos.split( '-' );
    	const dropPosition = info.dropPosition - Number( dropPos[dropPos.length - 1] );

    	if( dragType.startsWith( 'parent' ) ) {
    	    return;
    	}
    	
    	if( dragType.startsWith( 'node' ) && dropType.startsWith( 'node' ) ) {
    	    return;
    	}

    	const loop = ( data, key, callback ) => {
    		for ( let i = 0; i < data.length; i++ ) {
    			if ( data[i].key === key ) {
    				return callback( data[i], i, data );
    			}
    			if ( data[i].children ) {
    				loop( data[i].children, key, callback );
    			}
    		}
    	};
    	const data = [ ...this.state.groups ];

    	// Find dragObject
    	let dragObj;
    	loop( data, dragKey, ( item, index, arr ) => {
    		arr.splice( index, 1 );
    		dragObj = item;
    	} );

    	if ( !info.dropToGap ) {
    		// Drop on the content
    		loop( data, dropKey, item => {
    			item.children = item.children || [];
    			// where to insert 示例添加到头部，可以是随意位置
    			item.children.unshift( dragObj );
    		} );
    	} else if (
    		( info.node.props.children || [] ).length > 0 && // Has children
            info.node.props.expanded && // Is expanded
            dropPosition === 1 // On the bottom gap
    	) {
    		loop( data, dropKey, item => {
    			item.children = item.children || [];
    			// where to insert 示例添加到头部，可以是随意位置
    			item.children.unshift( dragObj );
    			// in previous version, we use item.children.push(dragObj) to insert the
    			// item to the tail of the children
    		} );
    	} else {
    		let ar;
    		let i;
    		loop( data, dropKey, ( item, index, arr ) => {
    			ar = arr;
    			i = index;
    		} );
    		if ( dropPosition === -1 ) {
    			ar.splice( i, 0, dragObj );
    		} else {
    			ar.splice( i + 1, 0, dragObj );
    		}
    	}

    	this.setState( {
    		groups: data,
    	} );
    };



    onExpand = ( expandedKeys ) => {
    	this.setState( { 'expandedKeys': expandedKeys } );
    }

    render() {
    	let title = '字段分组';
    	if( this.props.FieldData.edit ) {
    		title += ' (编辑)';
    	}
    	return (
    		<>
    			<Modal title={title} mask={false} maskClosable={false}
    				onCancel={this.handleCancle}
    				onOk={this.handleSubmit}
    				visible={this.props.modalVisibleValue}
    				okText={'确定'}
    				cancelText={'取消'}>
    				<Space direction={'vertical'} size={'middle'}>
    					<Space direction={'vertical'}>
    						<Typography>选择需分组的字段</Typography>
    						<Form ref={this.formRef}>
    							<Form.Item noStyle={true} name={'select'}>
    								<Select style={{ width: '180px' }} onChange={this.fieldChange}>
    									{
    										this.props.FieldData.model.fieldMappings.map(
    											( i,index ) => (
    												// 'i.tempFieldName}'
    												<Select.Option key={index} value={i.tempFieldName}>
    													{i.finalFieldDesc}
    												</Select.Option>
    											)
    										)
    									}
    								</Select>
    							</Form.Item>
    						</Form>
    					</Space>
    					<Card style={{ width: '480px' }}>
    						<Tree.DirectoryTree
    							checkable
    							switcherIcon={<></>}
    							onDragEnd={this.onDragEnd}
    							expandedKeys={this.state.expandedKeys}
    							onExpand={this.onExpand}
    							onDragEnter={this.onDragEnter}
    							onDrop={this.onDrop}
    							height={320}
    							draggable onCheck={this.onCheck}
    							treeData={[ ...this.state.groups ]}/>
    					</Card>
    					<Space size={'middle'}>
    						<Button onClick={this.addFile}>添加分组</Button>
    						<Button onClick={this.handleDel}>删除</Button>
    					</Space>
    				</Space>
    			</Modal>
    			<AddGroup createGropVisible={this.state.createGropVisible}
    				addGroup={this.addGroup}
    				handleVisible={this.handleVisible}/>
    		</>
    	);
    }
}

export default GroupField ;
